package control;

import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import model.Player;
import model.Square;
import view.PlayerRep;
import view.SquareRep;

public class MovementListener implements KeyListener{

	private final Player player;
	private final PlayerRep playRep;
	private Square[][] region;

	public MovementListener(final Player player, final PlayerRep playRep, final Square[][] region){
		this.player = player;
		this.playRep = playRep;
		this.region = region;
	}

	public void setRegion(final Square[][] region){
		this.region = region;
	}

	public void keyPressed(final KeyEvent e) {
		int x = 0;
		int y = 0;
		// Get direction of movement.
		if(e.getKeyChar()=='w'){
			y = -1;
		}else if(e.getKeyChar()=='a'){
			x = -1;
		}else if(e.getKeyChar()=='s'){
			y = 1;
		}else if(e.getKeyChar()=='d'){
			x = 1;
		}
		move(x, y);
	}

	public void move(final int x, final int y){
		// See if player is blocked.
		for(final Point p : player.getCorners()){
			final Square touchedSquare = region[(p.x+x)/SquareRep.WIDTH][(p.y+y)/SquareRep.HEIGHT];
			touchedSquare.removePellet();
			if(touchedSquare.isBlocking()){
				return;
			}
		}
		// If player isn't blocked, move.
		player.move(x, y);
		playRep.update();
	}


	public void keyReleased(final KeyEvent arg0) {
	}

	public void keyTyped(final KeyEvent arg0) {
	}

}
